package cn.tedu.order.tx;

import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.mapper.TxMapper;
import cn.tedu.order.service.OrderService;
import cn.tedu.order.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;
@Slf4j
@Primary
@Service
public class TxOrderService implements OrderService {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private TxMapper txMapper;
    @Autowired
    EasyIdClient easyIdClient;
    @Override
    public void create(Order order) {
        String xid = UUID.randomUUID().toString().replaceAll("-", "");
        TxAccountMessage accountMessage=new TxAccountMessage(order.getUserId(),order.getMoney(),xid);
        String json= JsonUtil.to(accountMessage);
        Message<String> msg= MessageBuilder.withPayload(json).build();
        rocketMQTemplate.sendMessageInTransaction("order-topic:account", msg, order);
        log.info("消息已经发送");

    }
//    本地事务，执行订单时保存
//    方法在事务监听器中被调用
    @Transactional
    public void doCreate(Order order,String xid){
        log.info("执行事务，保存订单");
        Long orderId=Long.valueOf(easyIdClient.nextId("order_business"));
        order.setId(orderId);
        orderMapper.create(order);
        log.info("订单已经保存");

    }
}
